package com.cloud.common.core.result;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Data;
import org.springframework.util.StreamUtils;

@Data
public class Result<T> implements Serializable {

    /**
     * 错误码 编码为了保持位数统一，使用字符类型 如 00101
     */
    private String code;
    /**
     * 提示信息
     */
    private String msg;
    /**
     * 数据
     */
    private T data;

    /**
     * 构造方法私有化，不允许外部new
     */
    private Result(){}


    private Result(T data) {
        this.code = ResultEnum.SUCCESS.getCode();
        this.msg = ResultEnum.SUCCESS.getMsg();
        this.data = data;
    }

    private Result(RespEnum respEnum) {
        this.code = respEnum.getCode();
        this.msg = respEnum.getMsg();
        this.data = null;
    }

    private Result(RespEnum respEnum,String msg) {
        this.code = respEnum.getCode();
        this.msg = respEnum.getMsg();
        if(msg!=null){
            this.msg=msg;
        }
        this.data = null;
    }

    private Result(RespEnum respEnum,T data) {
        this.code = respEnum.getCode();
        this.msg = respEnum.getMsg();
        this.data = data;
    }
    /**
     * 成功时候的调用
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>(data);
    }

    public static <T> Result<T> success() {
        return new Result<T>(ResultEnum.SUCCESS);
    }

    public static <T> Result<T> success(String msg) {
        return new Result<T>(ResultEnum.SUCCESS,msg);
    }

    /**
     * 返回带分页的信息
     *
     * @return
     */
    public static <T> Result page(List<T> data, Page page, Long total) {
        page.setTotal(total);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", data == null ? new ArrayList() : data);
        map.put("page", page == null ? new Page() : page);
        return new Result(map);
    }

    /**
     * 返回带错误提示的失败
     *
     * @param <T>
     * @param msg
     * @return
     */
    public static <T> Result<T> error(String msg) {
        return new Result<T>(ResultEnum.ERROR,msg);
    }

    public static <T> Result<T> error(T data) {
        return new Result<T>(ResultEnum.PARAM_ERROR,data);
    }

    public static <T> Result<T> error(RespEnum respEnum) {
        return new Result<T>(respEnum);
    }

    public static <T> Result<T> error(RespEnum respEnum,String msg) {
        if(respEnum==null){
            respEnum=ResultEnum.ERROR;
        }
        return new Result<T>(respEnum, msg);
    }
    /**
     * 请求是否成功
     * @return
     */
    public boolean iSuccess() {
        if(code!=null && ResultEnum.SUCCESS.getCode().equals(code)){
            return true;
        }
        return false;
    }
}
